package com.threeonemeeting.activity;

import java.util.Map;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.snda.lib.http.HttpUtil;
import com.snda.lib.http.ICallBack;
import com.snda.lib.http.TaskManager;
import com.snda.lib.ui.MessageBox;
import com.snda.lib.util.MiscHelper;
import com.threeonemeeting.Const;
import com.threeonemeeting.DataCenter;
import com.threeonemeeting.R;
import com.threeonemeeting.db.AppDBHelper;
import com.threeonemeeting.model.UserInfo;
import com.threeonemeeting.tab.BaseTabActivity;
import com.threeonemeeting.task.HttpConst;
import com.threeonemeeting.task.LoginTask;
import com.threeonemeeting.util.MiscUtil;

public class LoginActivity extends BaseTabActivity implements ICallBack {

	private boolean bAccountEdited = false; // 帐号框是否编辑过
	private boolean bPasswordEdited = false; // 密码框是否编辑过

	private String strJumpTo = "MainMy31Activity"; // 需要跳转到的目的Activity
	private Bundle b = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_login);

		Boolean bAddNewAccount = false;

		b = this.getIntent().getExtras();
		if (b != null) {
			strJumpTo = b.getString("jumpto");
			if (strJumpTo == null) {
				strJumpTo = "MainMy31Activity";
			}

			bAddNewAccount = b.getBoolean("add");
			if (bAddNewAccount == null)
				bAddNewAccount = false;

			b = b.getBundle("bundle");
		}

		if (bAddNewAccount == false) {

			// 检查用户是否已经登陆过
			String strMainUserId = MiscUtil
					.getPrefer(Const.Pref.PREFS_KEY_MAIN_USER_ID);

			String strCurrentUserId = MiscUtil
					.getPrefer(Const.Pref.PREFS_KEY_CURRENT_USER_ID);

			if (MiscHelper.isEmpty(strCurrentUserId) == false
					&& MiscHelper.isEmpty(strMainUserId) == false) {

				Integer nMainUserid = Integer.parseInt(strMainUserId);
				Integer nCurrentUserid = Integer.parseInt(strCurrentUserId);

				if (nCurrentUserid != null && nMainUserid != null) {

					// 检查用户的信息是否保存在数据库中
					AppDBHelper db = DataCenter.getInstance().getDB();
					DataCenter.getInstance().listAccounts = db
							.getAccount(nMainUserid);

					UserInfo uMainUserInfo = db.getMainAccount(nMainUserid);
					if (uMainUserInfo != null) {
						DataCenter.getInstance().mainLoginUser = uMainUserInfo;

						if (uMainUserInfo.nUserId == nCurrentUserid) {
							DataCenter.getInstance().currentLoginUserInfo = uMainUserInfo;
						} else {

							UserInfo uCurrentUserInfo = db.getAccount(
									nMainUserid, nCurrentUserid);
							if (uCurrentUserInfo != null) {
								DataCenter.getInstance().currentLoginUserInfo = uCurrentUserInfo;
							}
						}
					}

					uiHandler.sendEmptyMessage(0);
					return;
				}
			}
		}

		// 帐号框
		final EditText editAccount = (EditText) findViewById(R.id.editAccount);
		// editAccount.setText("是非");
		editAccount.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				String strHint = getResources().getString(
						R.string.string_input_account);
				String strAccount = editAccount.getText().toString();

				if (hasFocus == true) {
					if (strAccount.equalsIgnoreCase(strHint) == true) {
						editAccount.setText("");
					}

				} else {

					if (strAccount.equalsIgnoreCase("") == true) {
						editAccount.setText(strHint);
					}
				}
			}
		});
		editAccount.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				bAccountEdited = true;
				return false;
			}
		});

		// 密码框
		final EditText editPassword = (EditText) findViewById(R.id.editPassword);
		// editPassword.setText("plokmijn");
		editPassword.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {

				String strHint = getResources().getString(
						R.string.string_input_reg_password);
				String strPassword = editPassword.getText().toString();
				if (hasFocus == true) {

					if (strPassword.equalsIgnoreCase(strHint) == true) {
						editPassword.setText("");
						editPassword
								.setTransformationMethod(PasswordTransformationMethod
										.getInstance());
					}
				} else {

					if (strPassword.equalsIgnoreCase("") == true) {
						editPassword.setText(strHint);
						editPassword
								.setTransformationMethod(HideReturnsTransformationMethod
										.getInstance());
					}
				}
			}
		});
		editPassword.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				bPasswordEdited = true;
				return false;
			}
		});

		// 注册按钮
		Button btnRegister = (Button) findViewById(R.id.btn_register);
		OnClickListener hotMeetingBtnClickListener = new OnClickListener() {

			public void onClick(View v) {
				// strJumpTo
				Bundle b = new Bundle();
				b.putString("jumpto", strJumpTo);
				startActivity("RegisterActivity", b);
			}
		};
		btnRegister.setOnClickListener(hotMeetingBtnClickListener);

		// 登录按钮
		Button btnLogin = (Button) findViewById(R.id.btn_login);
		OnClickListener hotLoginBtnClickListener = new OnClickListener() {

			public void onClick(View v) {

				// 检查输入框和密码框的内容是否为空
				String strAccount = editAccount.getText().toString();
				String strPassword = editPassword.getText().toString();

				String strAccountHint = getResources().getString(
						R.string.string_input_account);
				String strPasswordHint = getResources().getString(
						R.string.string_input_reg_password);

				// 帐号输入框
				if (strAccount.equals("") == true) {
					MessageBox.showToast(LoginActivity.this, "帐号不能 为空");
					return;
				}

				if (bAccountEdited == false
						&& strAccount.equalsIgnoreCase(strAccountHint) == true) {
					MessageBox.showToast(LoginActivity.this, "帐号不能 为空");
					return;
				}

				// 密码输入框
				if (strPassword.equals("") == true) {
					MessageBox.showToast(LoginActivity.this, "密码不能 为空");
					return;
				}

				if (bPasswordEdited == false
						&& strPassword.equalsIgnoreCase(strPasswordHint) == true) {
					MessageBox.showToast(LoginActivity.this, "密码不能 为空");
					return;
				}

				// Util.showAlert(LoginActivity.this, "登录中", "正在登录，请稍候");

				// 发送请求
				// 上报应用崩溃的次数
				LoginTask task = new LoginTask(LoginActivity.this,
						LoginActivity.this);
				Bundle params = new Bundle();
				params.putString("user", strAccount);
				params.putString("pass", strPassword);
				TaskManager.addTask(task, params, true);
			}
		};
		btnLogin.setOnClickListener(hotLoginBtnClickListener);

		// 显示密码
		final CheckBox cbShowPasswd = (CheckBox) findViewById(R.id.cb_showpasswd);
		CheckBox.OnCheckedChangeListener cbShowPasswordChangeListener = new CheckBox.OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {

				if (cbShowPasswd.isChecked()) {
					editPassword
							.setTransformationMethod(HideReturnsTransformationMethod
									.getInstance());
				} else {

					String strHint = getResources().getString(
							R.string.string_input_reg_password);
					String strPassword = editPassword.getText().toString();

					if (strPassword.equalsIgnoreCase(strHint) == false) {
						editPassword
								.setTransformationMethod(PasswordTransformationMethod
										.getInstance());
					}
				}
			}
		};
		cbShowPasswd.setOnCheckedChangeListener(cbShowPasswordChangeListener);
	}

	@Override
	public boolean canBack() {

		if (strFromActivity == null
				|| strFromActivity.trim().equals("") == true)
			return false;

		if (strFromActivity.equalsIgnoreCase("MainMessageActivity") == true
				|| strFromActivity.equalsIgnoreCase("MainMy31Activity") == true)
			return false;

		return true;
	}

	// 通过Handler进行UI的更新
	Handler uiHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {

			// 更新
			case 0:
				if (b == null) {
					if (strFromActivity.equalsIgnoreCase(strJumpTo) == true) {
						startActivity("", strJumpTo);
					} else {
						startActivity(strFromActivity, strJumpTo);
					}
				} else {
					if (strFromActivity.equalsIgnoreCase(strJumpTo) == true) {
						startActivity("", strJumpTo, b);
					} else {
						startActivity(strFromActivity, strJumpTo, b);
					}
				}
				break;

			}
			super.handleMessage(msg);
		}
	};

	public void doCallBack(Map<String, Object> map) {
		Integer msgType = (Integer) map.get(HttpConst.KEY_TASK_TYPE);
		if (msgType == null) {
			Log.d(Const.Tag, "can't find type in response type");
			return;
		}

		Integer nError = (Integer) map.get(HttpUtil.KEY_ERROR_CODE);
		if (nError == null || nError != HttpUtil.ERROR_SUCCESS) {
			Log.d(Const.Tag, "response return error:" + nError + " type:"
					+ msgType);

			String strErrorMsg = (String) map.get(HttpUtil.KEY_ERROR_MSG);
			MessageBox.showToast(LoginActivity.this, strErrorMsg);
			return;
		}

		// 登录成功
		if (msgType == HttpConst.TASKTYPE_LOGIN) {
			uiHandler.sendEmptyMessage(0);

			UserInfo currentUserInfo = DataCenter.getInstance().currentLoginUserInfo;
			UserInfo mainUserInfo = DataCenter.getInstance().mainLoginUser;

			String strMainUserId = MiscUtil
					.getPrefer(Const.Pref.PREFS_KEY_CURRENT_USER_ID);
			if (MiscHelper.isEmpty(strMainUserId) == true) {
				MiscUtil.setPrefer(Const.Pref.PREFS_KEY_MAIN_USER_ID,
						String.valueOf(mainUserInfo.nUserId));
			}

			MiscUtil.setPrefer(Const.Pref.PREFS_KEY_CURRENT_USER_ID,
					String.valueOf(currentUserInfo.nUserId));
		}
	}
}
